package com.atguigu.process.service.impl;


import com.atguigu.model.process.ProcessType;
import com.atguigu.process.mapper.OaProcessTemplateMapper;
import com.atguigu.process.service.OaProcessService;
import com.atguigu.process.service.OaProcessTemplateService;
import com.atguigu.process.service.OaProcessTypeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atguigu.model.process.ProcessTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批模板 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2023-06-05
 */
@Service
public class OaProcessTemplateServiceImpl extends ServiceImpl<OaProcessTemplateMapper, ProcessTemplate> implements OaProcessTemplateService {



    @Autowired
    private OaProcessTypeService processTypeService;

    @Autowired
    private OaProcessService processService;

    //分页查询模板，将审批类型对应的名称查询出来
    @Override
    public IPage<ProcessTemplate> selectPage(Page<ProcessTemplate> pageParam) {
        //1.调用mapper实现分页查询
        Page<ProcessTemplate> processTemplatePage = baseMapper.selectPage(pageParam,null);
        //从分页数据获取列表list集合
        List<ProcessTemplate> processTemplateList = processTemplatePage.getRecords();
        //遍历list集合，得到审批类型的id
        for (ProcessTemplate processTemplate:processTemplateList) {
            //得到id
            Long processTypeId = processTemplate.getProcessTypeId();
            //根据id查询对应名称
            LambdaQueryWrapper<ProcessType> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProcessType::getId,processTypeId);
            ProcessType processType = processTypeService.getOne(wrapper);
            if (processType==null){
                continue;
            }
            //完成最终封装
            processTemplate.setProcessTypeName(processType.getName());
        }
        return processTemplatePage;
    }

    //1.完成在数据表中修改模板状态值，1为发布。2.完成流程定义的部署
    @Override
    public void publish(Long id) {
        //查出数据
        ProcessTemplate processTemplate = baseMapper.selectById(id);
        //修改状态
        processTemplate.setStatus(1);
        //更新数据
        baseMapper.updateById(processTemplate);

        //流程定义部署后续完善
        if (!StringUtils.isEmpty(processTemplate.getProcessDefinitionPath())){
            processService.deployByZip(processTemplate.getProcessDefinitionPath());
        }


    }
}
